<script lang="ts" setup>
import { usePermissionStore } from "@/pinia/stores/permission"
import { useSettingsStore } from "@/pinia/stores/settings"
import { setToken } from "@@/utils/cache/cookies"
import { Lock, User } from "@element-plus/icons-vue"
import type { FormInstance, FormRules } from "element-plus"
import { useFocus } from "./composables/useFocus"

const router = useRouter()
const { handleBlur, handleFocus } = useFocus()
const loginFormRef = ref<FormInstance | null>(null)
const loading = ref(false)
const permissionStore = usePermissionStore()
const settingsStore = useSettingsStore()

// 登录表单数据
const loginFormData = reactive({
  username: "admin",
  password: "123456"
})

const localUsers = reactive([
  { username: "admin", password: "123456" },
  { username: "test", password: "test1234" },
  { username: "guest", password: "guest8888" }
])

function setLoginState(username: string) {
  localStorage.setItem("isLoggedIn", "true")
  localStorage.setItem("currentUser", username)
}

// 登录表单校验规则
const loginFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ]
}

// 登录逻辑
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) return
    loading.value = true
    const matchedUser = localUsers.find(
      user => user.username === loginFormData.username && user.password === loginFormData.password
    )

    if (matchedUser) {
      ElMessage.success(`欢迎，${matchedUser.username}`)
      setLoginState(matchedUser.username)
      permissionStore.setAllRoutes()
      setToken("mock-token") // 登录成功后设置
      router.push("/") // 可跳转首页
    } else {
      ElMessage.error("用户名或密码错误")
    }
    loading.value = false
  })
}

// 页面加载初始化验证码
onMounted(() => {
  const isLoggedIn = localStorage.getItem("isLoggedIn") === "true"
  const username = localStorage.getItem("currentUser")
  if (isLoggedIn && username) {
    router.push("/") // 可跳转主界面
  }
})

</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <div class="title">
        数据处理分析与监控管理系统
      </div>
      <div class="content">
        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input v-model.trim="loginFormData.username" placeholder="用户名" type="text" tabindex="1"
              :prefix-icon="User" size="large" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="loginFormData.password" placeholder="密码" type="password" tabindex="2"
              :prefix-icon="Lock" size="large" show-password @blur="handleBlur" @focus="handleFocus" />
          </el-form-item>

          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleLogin">
            登 录
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  background-image: url("@/common/assets/images/bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .login-card {
    width: 460px;
    max-width: 90%;
    border-radius: 16px;
    padding: 30px 40px;
    background: rgba(9, 152, 241, 0.85); // 深色玻璃效果
    backdrop-filter: blur(10px);
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
    color: #e0e0e0;

    .title {
      text-align: center;
      font-size: 26px;
      font-weight: 600;
      margin-bottom: 20px;
      color: #7ae6a2;
      letter-spacing: 2px;
    }

    .content {
      .el-input__wrapper {
        background: rgba(255, 255, 255, 0.08) !important;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        color: #fff;
      }

      .el-input__inner {
        color: #fff;
      }

      .el-button {
        width: 100%;
        margin-top: 20px;
        background: linear-gradient(to right, #00c6ff, #86a3c6);
        border: none;
        color: white;
        font-weight: bold;
        font-size: 16px;
        box-shadow: 0 2px 10px rgba(0, 114, 255, 0.4);
        transition: all 0.3s ease;
      }

      .el-button:hover {
        filter: brightness(1.1);
        transform: translateY(-1px);
      }
    }
  }

}
</style>
